/*****  Component, by Ben Bi <prince.bi@gmail.com>  created at: 12/23/2009 4:10:45 PM  *****/

/********   Notes:  *******
 *  Two tags need to be replaced with the module name, they are:
 *  productionOrder
 *  ProductionOrder
 */



/***** variables declartion section, begin *****/
var productionOrderInputMode = wacFormInputMode.add;
var productionOrderObj = {};
var productionOrderAuditAction = {};  // process audit action

/***** variables declartion section, end *****/

/***** init section, begin *****/
$(document).ready(
    function() {
        productionOrderAuditAction = new ProductionOrderAuditAction();

        initProductionOrderFormDialog();

        initProductionOrderForm();

        bindProductionOrderEvents();
    }
);

function bindProductionOrderEvents()
{
    $("#productionOrderFormDialog").bind('dialogopen', function(event, ui)
    {
        initProductionOrderFormData();
//        wacDebugLog("calling " + moduleName + ":" + wacModelObj.productionOrder.name);//
    });

    $("#productionOrderFormDialog").bind('dialogclose', function(event, ui)
    {
        $.validationEngine.closePrompt(".formError", true);
    });

    $("#productionOrder_btnSubmit").bind('click', function (e)
    {
        submitProductionOrderForm();
    });

    $("#productionOrder_btnClose").bind('click', function (e)
    {
        $("#productionOrderFormDialog").dialog('close');
    });

    // fix dialog div didnt remove bug, remove it by this way
    $('#appStorehouseRightPane').bind('tabsremove', function(event, ui) {
        if(ui.panel.id == "t1004")
        {
            $("div[aria-labelledby='ui-dialog-title-productionOrderFormDialog']").remove();
            $("#productionOrderFormDialog").remove();
        }
    });
}


function initProductionOrderFormDialog()
{
//    wacDebugLog("initProductionOrderFormDialog.");
    $("#productionOrderFormDialog").dialog({
            bgiframe: true,
            modal: true,
            width: 850,
            height: 550,
            autoOpen: false,
            buttons: {},
            zIndex: 100
        });
}

function initProductionOrderForm()
{
    $("#productionOrderForm").validationEngine();

    $.datepicker.setDefaults($.datepicker.regional['zh-CN']);
    $("#productionOrder_start_date, #productionOrder_delivery_date").datepicker();
//    $("#start_date, #delivery_date").datepicker({
//        duration: '',
//        showTime: true,
//        constrainInput: false,
//        stepMinutes: 1,
//        stepHours: 1,
//        altTimeField: '',
//        time24h: false
//     });

    $('.wacFormContent .left, .wacFormContent input, .wacFormContent textarea, .wacFormContent select').focus(function(){
        $(this).parents('.wacFormContent').addClass("wacFormOver");
    }).blur(function(){
        $(this).parents('.wacFormContent').removeClass("wacFormOver");
    });
    
    $('.wacFormContentA .left, .wacFormContentA input, .wacFormContentA textarea, .wacFormContentA select').focus(function(){
        $(this).parents('.wacFormRow').addClass("wacFormOver");
    }).blur(function(){
        $(this).parents('.wacFormRow').removeClass("wacFormOver");
    });

    
}

function initProductionOrderFormData()
{
    wacShowBlockUILoading("#productionOrderFormDialog");
    $('#productionOrder_customer_order_id, #productionOrder_goods_category_id, #productionOrder_sample_jar_id,#productionOrder_goods_amount_unit_code, #productionOrder_currency_code ').empty();

    var params = {
        "data_format" :'json'
    };

    $.ajax({
        url: BASE_URL + "productionOrder/getFormData",
        global: true,
        type: "GET",
        data: params,
        dataType: "json",
        success: function(jsonData){
            initProductionOrderFormDataCallBack(jsonData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            wacDebugLog("getFormData Error: " + $(this).dump()); // the options for this ajax request
        }
    });
}

function initProductionOrderFormDataCallBack(jsonData)
{
   if(jsonData.info.status == wacOperationStatus.Error)
   {
       alert(jsonData.info.error_info);
   }
   else
    {
        var selectedIndex = 0;

        for(i=0;i<jsonData['items']['unit'].length;i++)
        {
            $('<option value="' + jsonData['items']['unit'][i].key +'">' + jsonData['items']['unit'][i].value +'</option>').appendTo("#productionOrder_goods_amount_unit_code");
        }

        for(i=0;i<jsonData['items']['currency'].length;i++)
        {
            $('<option value="' + jsonData['items']['currency'][i].key +'">' + jsonData['items']['currency'][i].value +'</option>').appendTo("#productionOrder_currency_code");
        }
   }

   setupProductOrderFormDefaultValues(jsonData['items']['default']);

   wacHideBlockUI("#productionOrderFormDialog");

//   wacDebugLog($.dump(jsonData));
}

function setupProductOrderFormDefaultValues(defaultValueObj)
{
    if(productionOrderInputMode == wacFormInputMode.add)   // use default values
    {
        $("#productionOrder_id").attr("value", 0);
        $('#productionOrder_goods_category_id').flexbox(BASE_URL + 'goodsCategory/GetProductHashInFormat?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "goods_category_id",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });

        $('#productionOrder_customer_order_id').flexbox(BASE_URL + 'customerOrder/GetIdCodeHashInFormat/status/audited?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "customer_order_id",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });

        $('#productionOrder_sample_jar_id').flexbox(BASE_URL + 'sampleJar/GetIdNameHashInFormat?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "sample_jar_id",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });

        $("#productionOrder_goods_amount_unit_code option:[value='"+ defaultValueObj.cloth_unit_code +"']").attr('selected', 'selected');
        $("#productionOrder_currency_code option:[value='"+ defaultValueObj.currency +"']").attr('selected', 'selected');
    }
    else  // use edit obj values
    {
        $('#productionOrder_goods_category_id').flexbox(BASE_URL + 'goodsCategory/GetProductHashInFormat?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            initialValue: productionOrderObj.goods_category_id,
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "goods_category_id",
            onSelect: function() {
                wacDebugLog('You selected "' + this.value + '", ' +
                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });
        $('#productionOrder_goods_category_id_input').val(productionOrderObj.goods_category_name);

        $('#productionOrder_customer_order_id').flexbox(BASE_URL + 'customerOrder/GetIdCodeHashInFormat/status/audited?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            initialValue: productionOrderObj.customer_order_id,
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "customer_order_id",
            onSelect: function() {
                wacDebugLog('You selected "' + this.value + '", ' +
                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });
        $('#productionOrder_customer_order_id_input').val(productionOrderObj.customer_order_code);

        $('#productionOrder_sample_jar_id').flexbox(BASE_URL + 'sampleJar/GetIdNameHashInFormat?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            initialValue: productionOrderObj.sample_jar_id,
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "sample_jar_id",
            onSelect: function() {
                wacDebugLog('You selected "' + this.value + '", ' +
                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });
        $('#productionOrder_sample_jar_id_input').val(productionOrderObj.sample_jar_name);

        $("#productionOrder_start_date").attr("value", productionOrderObj.start_date);
        $("#productionOrder_delivery_date").attr("value", productionOrderObj.delivery_date);
        $("#productionOrder_code").attr("value", productionOrderObj.code);
        $("#productionOrder_goods_amount").attr("value", productionOrderObj.goods_amount);
        $("#productionOrder_id").attr("value", productionOrderObj.id);
        $("#productionOrder_memo").attr("value", productionOrderObj.memo);

//        $("#productionOrder_goods_category_id option:[value='"+ productionOrderObj.goods_category_id +"']").attr('selected', 'selected');
        $("#productionOrder_goods_amount_unit_code option:[value='"+ productionOrderObj.goods_amount_unit_code +"']").attr('selected', 'selected');
        $("#productionOrder_currency_code option:[value='"+ productionOrderObj.currency_code +"']").attr('selected', 'selected');
    }

//    wacDebugLog($.dump(productionOrderObj));
//    wacDebugLog($.dump(defaultValueObj));
//    wacDebugLog("productionOrderInputMode: " + productionOrderInputMode);

}
/***** init section, end *****/


/**************  interaction section, begin  ***************/
// audit class
function ProductionOrderAuditAction(){
    this.run = function(orderId){
        productionOrderAudit(orderId);
    }
}

function productionOrderAudit(orderId)
{
    wacShowBlockUILoading();
    var params = {
        "data_format" : 'json',
        "production_order_id" : orderId
    };
//    productionOrderObj = $("#productionOrderList").getRowData(orderId);
//    console.log($.dump(productionOrderObj));

    $.ajax({
        url: BASE_URL + "productionOrder/audit",
        global: true,
        type: "GET",
        data: params,
        dataType: "json",
        success: function(jsonData){
            productionOrderAuditCallBack(jsonData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            wacDebugLog("getFormData Error: " + $(this).dump()); // the options for this ajax request
        }
    });
}

function productionOrderAuditCallBack(jsonData)
{
   if(jsonData.info.status == wacOperationStatus.Error)
   {
       wacShowTips(jsonData.info.error_info);
   }
   else
   {
       wacShowTips(jsonData.info.tips);
       $("#productionOrderList").trigger("reloadGrid");
   }
   wacHideBlockUI();
//   wacDebugLog($.dump(jsonData));
}

function productionOrderOpenModuleForm(moduleFormName, moduleName, inputMode, rowid)
{
    productionOrderInputMode = inputMode;

    if(rowid === undefined){
        productionOrderObj = {};
    }
    else
    {
        productionOrderObj = $("#" + moduleName +"List").getRowData(rowid);
    }

    $('#'+moduleFormName).dialog('open');
}

function validateProductionOrderForm()
{
    var validateFlag = true;
    
    if (!$("#productionOrderForm").validationEngine({returnIsValid:true}))
    {
        validateFlag = false;
        return validateFlag;
    }

    var startDate    = $("#productionOrder_start_date").datepicker( 'getDate' );
    var deliveryDate = $("#productionOrder_delivery_date").datepicker( 'getDate' );
    if(deliveryDate <= startDate)
    {
        wacShowTips("发货日期不得早于开始日期!");
        validateFlag = false;
    }
    
    return validateFlag;
}

function submitProductionOrderForm()
{
    if(!validateProductionOrderForm()){
        return;
    }

    wacShowBlockUILoading("#productionOrderFormDialog", "处理中...");

    var extraParams = "data_format=json";
    var submitUrl;

    if(productionOrderInputMode == wacFormInputMode.add){
        submitUrl = BASE_URL + "productionOrder/add";
    }
    else{
        submitUrl = BASE_URL + "productionOrder/edit";
    }


    $.ajax({
        url: submitUrl,
//        url: BASE_URL + "test/ajaxTest" ,
        global: true,
        type: "GET",
        data: $("#productionOrderForm").serialize() + "&" + extraParams,
        dataType: "json",
        success: function(jsonData){
            submitProductionOrderFormCallBack(jsonData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            wacDebugLog("getFormData Error: " + $(this).dump()); // the options for this ajax request
        }
    });
}

function submitProductionOrderFormCallBack(jsonData)
{
   if(jsonData.info.status == wacOperationStatus.Error)
   {
       wacShowTips(jsonData.info.error_info);
   }
   else
   {
       wacShowTips(jsonData.info.tips);
       $("#productionOrderList").trigger("reloadGrid");
   }

   wacHideBlockUI("#productionOrderFormDialog");

//   wacDebugLog($.dump(jsonData));
}

/**************  interaction section, end  ***************/